package cn.bugstack.mybatis.session.defaults;

import cn.bugstack.mybatis.binding.MapperRegistry;
import cn.bugstack.mybatis.executor.Executor;
import cn.bugstack.mybatis.mapping.Environment;
import cn.bugstack.mybatis.session.Configuration;
import cn.bugstack.mybatis.session.SqlSession;
import cn.bugstack.mybatis.session.SqlSessionFactory;
import cn.bugstack.mybatis.session.TransactionIsolationLevel;
import cn.bugstack.mybatis.transaction.Transaction;
import cn.bugstack.mybatis.transaction.TransactionFactory;

public class DefaultSqlSessionFactory implements SqlSessionFactory {

//    private final MapperRegistry mapperRegistry;
//
//
//
//
//
//    public DefaultSqlSessionFactory(MapperRegistry mapperRegistry){
//        this.mapperRegistry = mapperRegistry;
//    }

    private final Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

//    @Override
//    public SqlSession openSession(){
//        return new DefaultSqlSession(mapperRegistry);
//    }


//    @Override
//    public SqlSession openSession() {
//        return new DefaultSqlSession(configuration);
//    }




    // 第七章修改
    @Override
    public SqlSession openSession() {
       Transaction tx = null;
       try{
           final Environment environment = configuration.getEnvironment();
           TransactionFactory transactionFactory = environment.getTransactionFactory();
           tx = transactionFactory.newTransaction(environment.getDataSource(), TransactionIsolationLevel.READ_COMMITTED, false);
           final Executor executor = configuration.newExecutor(tx);
           return new DefaultSqlSession(configuration, executor);

       }catch (Exception e){

           try {
               assert tx != null;
               tx.close();
           } catch (Exception ignore) {
               // Ignore.
           }
            throw new RuntimeException("Error opening session.  Cause: " + e);
       }
    }
}
